package com.njtoyo.taxi.admin.service.data.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.handler.DateTimeHandler;
import com.njtoyo.taxi.admin.handler.FilterHandler;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.mapper.master.entity.*;
import com.njtoyo.taxi.admin.mapper.master.enums.RideOrderState;
import com.njtoyo.taxi.admin.mapper.master.enums.RideStateState;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.mapper.secondary.entity.data.DashboardCallMinute;
import com.njtoyo.taxi.admin.mapper.secondary.entity.data.DashboardCustomerMinute;
import com.njtoyo.taxi.admin.mapper.secondary.entity.data.DashboardIncomeMinute;
import com.njtoyo.taxi.admin.mapper.secondary.entity.data.DashboardOrderMinute;
import com.njtoyo.taxi.admin.mapper.secondary.enums.DataIncomeThroughType;
import com.njtoyo.taxi.admin.mapper.secondary.enums.DataOrderType;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.AdminUserMapper;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.data.*;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.AdminUserIdentityPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.data.data_analysis.TodayWrapper;
import com.njtoyo.taxi.admin.service.data.TodayAnalysisService;
import com.taxi.entity.common.RestResult;
import com.njtoyo.taxi.entity.backend.AdminUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@DS(Const.SECONDARY_DS)
public class TodayAnalysisServiceImpl implements TodayAnalysisService {

    @Autowired
    private DashboardOrderMinuteMapper dashboardOrderMinuteMapper;

    @Autowired
    private DashboardIncomeMinuteMapper dashboardIncomeMinuteMapper;

    @Autowired
    private DashboardCallMinuteMapper dashboardCallMinuteMapper;

    @Autowired
    private DashboardCustomerMinuteMapper dashboardCustomerMinuteMapper;

    @Autowired
    private TaxiMapper taxiMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private GeoCantonAreaMapper geoCantonAreaMapper;

    @Autowired
    private GeoAreaMapper geoAreaMapper;
    @Autowired
    private DriverStartServiceMapper driverStartServiceMapper;
    @Autowired
    private SysRegionMapper regionMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private RealtimeCallMapper realtimeCallMapper;
    @Autowired
    private DriverGrabRealtimePersistedMapper driverGrabRealtimePersistedMapper;
    @Autowired
    private DriverConfirmCallPersistedMapper driverConfirmCallPersistedMapper;
    @Autowired
    private RideOrderMapper rideOrderMapper;
    @Autowired
    private FunnelMapper funnelMapper;
    @Autowired
    private RideStateMapper rideStateMapper;

    @Override
    public RestResult today(AdminUser adminUser, TodayWrapper wrapper) {
        FilterHandler filterHandler = new FilterHandler(adminUser, wrapper.getCantonId(), wrapper.getCompanyId());
        DateTimeHandler timeHandler = new DateTimeHandler();

        Map<String, Object> res = new HashMap<>();
        // 订单,呼叫
        if (adminUser.getResourceNames().contains("data_analysis_today_order")) {
            Map<String, Object> rideData = getRideData(filterHandler, timeHandler);
            res.put("order", rideData);
            res.put("call", getCallData(filterHandler, timeHandler, rideData));
        }
        // 收入
        if (adminUser.getResourceNames().contains("data_analysis_today_income")) {
            res.put("income", getIncomeData(filterHandler, timeHandler));
        }
        // 车俩
        if (adminUser.getResourceNames().contains("data_analysis_today_taxi")) {
            Map<String, Object> taxiMap = getTaxiData(filterHandler);
            List<Map<String, Object>> workingDrives = (List<Map<String, Object>>) taxiMap.get("workingDrives");
            if (CollUtil.isNotEmpty(workingDrives)) {
                List<Long> driverIds = workingDrives.stream().map(map -> MapUtil.getLong(map, "driverId")).collect(Collectors.toList());
                List<DriverStartServiceEntity> driverStarters = driverStartServiceMapper.selectList(Wrappers.<DriverStartServiceEntity>lambdaQuery()
                        .in(DriverStartServiceEntity::getDriverId, driverIds).eq(DriverStartServiceEntity::getInService, 1));
                Integer appCount = driverStarters.stream().filter(entity -> entity.getFromAuto() == 0).collect(Collectors.toList()).size();
                Integer appAuto = driverStarters.stream().filter(entity -> entity.getFromAuto() == 1).collect(Collectors.toList()).size();
                taxiMap.put("appCount", appCount);
                taxiMap.put("autoCount", appAuto);
            }

            res.put("taxi", taxiMap);

        }

        return RestResult.success(res);
    }

    @Override
    public RestResult todayOpen(String adCode) {
        Map<String, Object> res = new HashMap<>();

        Long cantonId = null;
        List<Long> cantonIdArry = new ArrayList<>();
        AdminUserIdentityPresenter adminUserIdentityPresenter = new AdminUserIdentityPresenter();
        if (StrUtil.isNotBlank(adCode)) {
            List<SysRegion> regions = regionMapper.selectList(Wrappers.<SysRegion>lambdaQuery().like(SysRegion::getMergerId, adCode));
            if (CollUtil.isEmpty(regions)) {
                return RestResult.success(res);
            }
            List<String> adcodes = regions.stream().map(SysRegion::getRegionId).collect(Collectors.toList());
            List<GeoArea> geoAreas = geoAreaMapper.selectList(Wrappers.<GeoArea>lambdaQuery().in(GeoArea::getAdCode, adcodes));
            if (CollUtil.isEmpty(geoAreas)) {
                return RestResult.success(res);
            }
            List<Long> areaIds = geoAreas.stream().map(GeoArea::getId).collect(Collectors.toList());
            List<GeoCantonArea> geoCantonAreaList = geoCantonAreaMapper.selectList(Wrappers.<GeoCantonArea>lambdaQuery().in(GeoCantonArea::getAreaId, areaIds));
            if (CollUtil.isEmpty(geoCantonAreaList)) {
                return RestResult.success(res);
            }
            cantonId = geoCantonAreaList.get(0).getCantonId();
            cantonIdArry = geoCantonAreaList.stream().map(GeoCantonArea::getCantonId).collect(Collectors.toList());
            res.put("cantonIdArry", cantonIdArry);
        }

        com.njtoyo.taxi.admin.mapper.secondary.entity.AdminUser adminUserEntity = adminUserMapper.selectById(3L);
        AdminUser adminUser = BeanUtil.copyProperties(adminUserEntity, AdminUser.class);
        adminUser.setIdentity(adminUserIdentityPresenter);
        FilterHandler filterHandler = new FilterHandler(adminUser, cantonId, null);
        DateTimeHandler timeHandler = new DateTimeHandler();
        filterHandler.setCantonIds((List<Long>) res.get("cantonIdArry"));
        // 订单,呼叫
        Map<String, Object> rideData = getOpenRideData(filterHandler, timeHandler);
        res.put("order", rideData);
        res.put("call", getOpenCallData(filterHandler, timeHandler, rideData));
        // 收入
        res.put("income", getOpenIncomeData(filterHandler, timeHandler));
        // 车俩
        res.put("taxi", getTaxiData(filterHandler));

        return RestResult.success(res);
    }

    @Override
    public Map<String, Object> rideJoinDriver(String callId) {
        RealtimeCall realtimeCall = realtimeCallMapper.selectById(callId);
        String passengerLocate = realtimeCall.getOrigin().getLongitude() + "," + realtimeCall.getOrigin().getLatitude();
        List<Map<String, Object>> drivers = driverMapper.getRideJoinDriver(callId);
        DriverGrabRealtimePersisted driverGrabRealtimePersisted = driverGrabRealtimePersistedMapper.selectOne(
                Wrappers.<DriverGrabRealtimePersisted>lambdaQuery().eq(DriverGrabRealtimePersisted::getRealtimeCallId, callId));
        for (Map<String, Object> map : drivers) {
            Long driverId = MapUtil.getLong(map, "driverId");
            List<DriverConfirmCallPersisted> confirmCallPersisteds = driverConfirmCallPersistedMapper.selectList(Wrappers.<DriverConfirmCallPersisted>lambdaQuery()
                    .eq(DriverConfirmCallPersisted::getDriverId, driverId)
                    .eq(DriverConfirmCallPersisted::getCallId, callId));
            map.put("receiveDate", CollUtil.isNotEmpty(confirmCallPersisteds) ? confirmCallPersisteds.get(0).getCreatedAt() : "-");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("passengerLocate", passengerLocate);
        result.put("drivers", drivers);
        result.put("joinedriverIds", ObjectUtil.isNull(driverGrabRealtimePersisted) ? "" : driverGrabRealtimePersisted.getJoinedDriverIds());
        result.put("winnerDriverId", ObjectUtil.isNull(driverGrabRealtimePersisted) ? "" : driverGrabRealtimePersisted.getWinnerDriverId());
        result.put("sendCallDate", realtimeCall.getCreatedAt());
        return result;
    }

    @Override
    public RestResult<?> getGrapNum() {
        Date todayStart = DateUtil.beginOfDay(DateUtil.date());
        Date todayEnd = DateUtil.endOfDay(DateUtil.date());
        List<Map<String, Object>> todayConfirms = driverConfirmCallPersistedMapper.selectCountGroupByHour(todayStart, todayEnd);
        List<Map<String, Object>> yesterdayConfirms = driverConfirmCallPersistedMapper.selectCountGroupByHour(DateUtil.offsetDay(todayStart, -1), DateUtil.offsetDay(todayEnd, -1));
        List<Map<String, Object>> weekAgoConfirms = driverConfirmCallPersistedMapper.selectCountGroupByHour(DateUtil.offsetDay(todayStart, -7), DateUtil.offsetDay(todayEnd, -7));

        List<Map<String, Object>> todayGrabs = driverGrabRealtimePersistedMapper.selectCountGroupByHour(todayStart, todayEnd);
        List<Map<String, Object>> yesterdayGrabs = driverGrabRealtimePersistedMapper.selectCountGroupByHour(DateUtil.offsetDay(todayStart, -1), DateUtil.offsetDay(todayEnd, -1));
        List<Map<String, Object>> weekAgoGrabs = driverGrabRealtimePersistedMapper.selectCountGroupByHour(DateUtil.offsetDay(todayStart, -7), DateUtil.offsetDay(todayEnd, -7));

        Map<String, Object> result = new HashMap<>();
        result.put("todayConfirms", todayConfirms);
        result.put("yesterdayConfirms", yesterdayConfirms);
        result.put("weekAgoConfirms", weekAgoConfirms);
        result.put("todayGrabs", todayGrabs);
        result.put("yesterdayGrabs", yesterdayGrabs);
        result.put("weekAgoGrabs", weekAgoGrabs);

        return RestResult.success(result);
    }

    @Override
    public RestResult<?> getDoneOrderByHour() {
//        Date todayStart = DateUtil.beginOfDay(DateUtil.date());
//        Date todayEnd = DateUtil.endOfDay(DateUtil.date());
//        List<Map<String, Object>> todayOrders = rideOrderMapper.selectByHour(RideOrderState.done, todayStart, todayEnd);
//
//        List<Map<String, Object>> yesterdayOrders = rideOrderMapper.selectByHour(RideOrderState.done, DateUtil.offsetDay(todayStart, -1), DateUtil.offsetDay(todayEnd, -1));
//
//        List<Map<String, Object>> weekAgoOrders = rideOrderMapper.selectByHour(RideOrderState.done, DateUtil.offsetDay(todayStart, -7), DateUtil.offsetDay(todayEnd, -7));
//
//        Map<String, Object> result = new HashMap<>();
//        result.put("todayOrders", todayOrders);
//        result.put("yesterdayOrders", yesterdayOrders);
//        result.put("weekAgoOrders", weekAgoOrders);
        return RestResult.success();
    }

    @Override
    public RestResult<?> getFinishOrderByDay() {
        Date todayEnd = DateUtil.date();
        Date todayStart = DateUtil.beginOfMonth(todayEnd);

        List<Map<String, Object>> dayOrders = rideOrderMapper.selectMaps(Wrappers.<RideOrder>query()
                .select("DATE_FORMAT(created_at, '%Y-%m-%d') AS dayDate,COUNT(*) AS count")
                .lambda()
                .between(RideOrder::getCreatedAt, todayStart, todayEnd)
                .eq(RideOrder::getState, RideOrderState.done)
                .last("group by dayDate"));
        Map<String, Object> result = new HashMap<>();
        result.put("dayOrders", dayOrders);
        return RestResult.success(result);
    }

    @Override
    public RestResult<?> getCancelAnalyse() {
        Date todayStart = DateUtil.beginOfDay(DateUtil.date());
        Date todayEnd = DateUtil.endOfDay(DateUtil.date());

        List<Map<String, Object>> listMap = funnelMapper.getRideCancelAnalyse(todayStart, todayEnd);

        Map<String, Object> result = new HashMap<>();


        long cancelWithin1Minute = listMap.stream()
                .filter(ride -> DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) < 1).count();
        long cancelWithin2Minute = listMap.stream()
                .filter(ride -> DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) >= 1 &&
                        DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) < 2).count();
        long cancelWithin3Minute = listMap.stream()
                .filter(ride -> DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) >= 2 &&
                        DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) < 3).count();
        long cancelWithin4Minute = listMap.stream()
                .filter(ride -> DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) >= 3 &&
                        DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) < 4).count();
        long cancelWithin5Minute = listMap.stream()
                .filter(ride -> DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) >= 4 &&
                        DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) < 5).count();
        long cancelWithin5LaterMinute = listMap.stream()
                .filter(ride -> DateUtil.between(MapUtil.getDate(ride, "cancelTime"), MapUtil.getDate(ride, "rideTime"), DateUnit.MINUTE) >= 5).count();


        result.put("cancelWithin1Minute", CollUtil.isNotEmpty(listMap) ? cancelWithin1Minute : 0);
        result.put("cancelWithin2Minute", CollUtil.isNotEmpty(listMap) ? cancelWithin2Minute : 0);
        result.put("cancelWithin3Minute", CollUtil.isNotEmpty(listMap) ? cancelWithin3Minute : 0);
        result.put("cancelWithin4Minute", CollUtil.isNotEmpty(listMap) ? cancelWithin4Minute : 0);
        result.put("cancelWithin5Minute", CollUtil.isNotEmpty(listMap) ? cancelWithin5Minute : 0);
        result.put("cancelWithin5LaterMinute", CollUtil.isNotEmpty(listMap) ? cancelWithin5LaterMinute : 0);
        result.put("cancelCount", CollUtil.isNotEmpty(listMap) ? listMap.size() : 0);


        return RestResult.success(result);
    }


    /**
     * 乘客数据
     */
    private Map<String, Object> getCustomerData(FilterHandler filterHandler, DateTimeHandler time) {
        Map<String, Object> customerData = new HashMap<>();

        QueryWrapper<DashboardCustomerMinute> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(SUM(num), 0) as total");
        switch (filterHandler.getFilterType()) {
            case canton:
            case company:
                queryWrapper.in("canton_id", filterHandler.getCantonIds());
        }

        QueryWrapper<DashboardCustomerMinute> queryWrapperYesterday = queryWrapper.clone(), queryWrapperLastWeek = queryWrapper.clone();

        queryWrapper.between("stats_date", time.getTodayBeginning(), time.getToday());
        queryWrapperYesterday.between("stats_date", time.getYesterdayBeginning(), time.getYesterdaySameTime());
        queryWrapperLastWeek.ge("stats_date", time.getLastWeekBeginning()).le("stats_date", time.getLastWeekSameTime());

        customerData.put("today", dashboardCustomerMinuteMapper.selectObjs(queryWrapper).get(0));
        customerData.put("yesterday", dashboardCustomerMinuteMapper.selectObjs(queryWrapperYesterday).get(0));
        customerData.put("lastWeek", dashboardCustomerMinuteMapper.selectObjs(queryWrapperLastWeek).get(0));

        // 翻倍率
        Double customer = filterHandler.getFakeMultiple().getCustomer();
        if (Objects.nonNull(customer)) {
            customerData.forEach((k, v) -> customerData.put(k, (int) (Integer.parseInt(v.toString()) * customer)));
        }

        return customerData;
    }

    /**
     * 车俩数据
     */
    private Map<String, Object> getTaxiData(FilterHandler filterHandler) {
        Map<String, Object> taxiData = new HashMap<>();
        Long totalCount = 0L, workingCount = 0L, ridingCount = 0L;
        List<Map<String, Object>> workingDrives = new ArrayList<>();
        System.out.println(filterHandler);
        switch (filterHandler.getFilterType()) {
            case platform:
                totalCount = taxiMapper.getUnScrappedTotalCount(null, null);
                workingCount = taxiMapper.getWorkingTotalCount(null, null);
                ridingCount = taxiMapper.getRidingTotalCount(null, null);
                workingDrives = taxiMapper.getWorkingDrives(null, null);
                break;
            case canton:
                totalCount = taxiMapper.getUnScrappedTotalCount(filterHandler.getCantonIds(), null);
                workingCount = taxiMapper.getWorkingTotalCount(filterHandler.getCantonIds(), null);
                ridingCount = taxiMapper.getRidingTotalCount(filterHandler.getCantonIds(), null);
                break;
            case company:
                totalCount = taxiMapper.getUnScrappedTotalCount(null, filterHandler.getCompanyIds());
                workingCount = taxiMapper.getWorkingTotalCount(null, filterHandler.getCompanyIds());
                ridingCount = taxiMapper.getRidingTotalCount(null, filterHandler.getCompanyIds());
                break;
        }
        Double taxiRate = filterHandler.getFakeMultiple().getWorkingTaxiRate();
        if (Objects.nonNull(taxiRate)) {
            totalCount = (long) (Long.parseLong(totalCount.toString()) * taxiRate);
            workingCount = (long) (Long.parseLong(workingCount.toString()) * taxiRate);
            ridingCount = (long) (Long.parseLong(ridingCount.toString()) * taxiRate);
        }
        taxiData.put("total", totalCount);
        taxiData.put("working", workingCount);
        taxiData.put("workingDrives", workingDrives);
        taxiData.put("riding", ridingCount);

        return taxiData;
    }

    /**
     * 呼叫数据
     */
    private Map<String, Object> getCallData(FilterHandler filterHandler, DateTimeHandler time, Map<String, Object> rideData) {
        Map<String, Object> callData = new HashMap<>();

        QueryWrapper<DashboardCallMinute> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(SUM(num), 0) as total");
        switch (filterHandler.getFilterType()) {
            case canton:
            case company:
                queryWrapper.in("canton_id", filterHandler.getCantonIds());
                break;
        }

        QueryWrapper<DashboardCallMinute> queryWrapperYesterday = queryWrapper.clone(), queryWrapperLastWeek = queryWrapper.clone();

        queryWrapper.between("stats_date", time.getTodayBeginning(), time.getToday());
        queryWrapperYesterday.between("stats_date", time.getYesterdayBeginning(), time.getYesterdaySameTime());
        queryWrapperLastWeek.ge("stats_date", time.getLastWeekBeginning()).le("stats_date", time.getLastWeekSameTime());

        callData.put("today", dashboardCallMinuteMapper.selectObjs(queryWrapper).get(0));
        callData.put("yesterday", dashboardCallMinuteMapper.selectObjs(queryWrapperYesterday).get(0));
        callData.put("lastWeek", dashboardCallMinuteMapper.selectObjs(queryWrapperLastWeek).get(0));

        // 翻倍率
        Double call = filterHandler.getFakeMultiple().getCall();
        if (Objects.nonNull(call)) {
            callData.forEach((k, v) -> {
                int callCount = (int) (Integer.parseInt(v.toString()) * call);
                // 如果 call 数量小于了 ride 数
                if (callCount < (int) rideData.get(k)) {
                    callCount = (int) (Integer.parseInt(rideData.get(k).toString()) * 1.215);
                }
                callData.put(k, callCount);
            });
        }
        return callData;
    }

    private Map<String, Object> getOpenCallData(FilterHandler filterHandler, DateTimeHandler time, Map<String, Object> rideData) {
        Map<String, Object> callData = new HashMap<>();

        QueryWrapper<DashboardCallMinute> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(SUM(num), 0) as total");
        switch (filterHandler.getFilterType()) {
            case canton:
            case company:
                queryWrapper.in("canton_id", filterHandler.getCantonIds());
                break;
        }

        QueryWrapper<DashboardCallMinute> queryWrapperYesterday = queryWrapper.clone(), queryWrapperLastWeek = queryWrapper.clone();

        queryWrapper.between("stats_date", time.getTodayBeginning(), time.getToday());
        queryWrapperYesterday.between("stats_date", time.getYesterdayBeginning(), time.getYesterdayEnd());
        queryWrapperLastWeek.ge("stats_date", time.getLastWeekBeginning()).le("stats_date", time.getLastWeekSameTime());

        callData.put("today", dashboardCallMinuteMapper.selectObjs(queryWrapper).get(0));
        callData.put("yesterday", dashboardCallMinuteMapper.selectObjs(queryWrapperYesterday).get(0));
        callData.put("lastWeek", dashboardCallMinuteMapper.selectObjs(queryWrapperLastWeek).get(0));

        // 翻倍率
        Double call = filterHandler.getFakeMultiple().getCall();
        if (Objects.nonNull(call)) {
            callData.forEach((k, v) -> {
                int callCount = (int) (Integer.parseInt(v.toString()) * call);
                // 如果 call 数量小于了 ride 数
                if (callCount < (int) rideData.get(k)) {
                    callCount = (int) (Integer.parseInt(rideData.get(k).toString()) * 1.215);
                }
                callData.put(k, callCount);
            });
        }
        return callData;
    }


    /**
     * 获取订单数据
     */
    private Map<String, Object> getOpenRideData(FilterHandler filterHandler, DateTimeHandler time) {
        Map<String, Object> orderData = new HashMap<>();

        QueryWrapper<DashboardOrderMinute> queryWrapper = new QueryWrapper<>();
        QueryWrapper<DashboardOrderMinute> todayQuery = new QueryWrapper<>();
        todayQuery.in("type", DataOrderType.simpleCall, DataOrderType.phoneCall)
                .in("is_imitate", filterHandler.getIsImitates())
                .between("stats_date", time.getTodayBeginning(), time.getToday())
                .select("type, IFNULL(SUM(num), 0) as total")
                .groupBy("type");

        queryWrapper.in("type", DataOrderType.pickOnline, DataOrderType.pickScan, DataOrderType.simpleCall, DataOrderType.phoneCall);
        queryWrapper.in("is_imitate", filterHandler.getIsImitates());
        queryWrapper.select("IFNULL(SUM(num), 0) as total");
        switch (filterHandler.getFilterType()) {
            case canton:
                queryWrapper.in("canton_id", filterHandler.getCantonIds());
                todayQuery.in("canton_id", filterHandler.getCantonIds());
                break;
            case company:
                queryWrapper.in("company_id", filterHandler.getCompanyIds());
                todayQuery.in("company_id", filterHandler.getCompanyIds());
        }
        QueryWrapper<DashboardOrderMinute> queryWrapperYesterday = queryWrapper.clone(), queryWrapperLastWeek = queryWrapper.clone();

        queryWrapper.between("stats_date", time.getTodayBeginning(), time.getToday());
        queryWrapperYesterday.between("stats_date", time.getYesterdayBeginning(), time.getYesterdayEnd());
        queryWrapperLastWeek.ge("stats_date", time.getLastWeekBeginning()).le("stats_date", time.getLastWeekSameTime());

        // 今日订单
        List<Map<String, Object>> mapList = dashboardOrderMinuteMapper.selectMaps(todayQuery);
        Map<Object, Object> objectMap = mapList.stream().collect(Collectors.toMap(e -> e.get("type"), e -> e.get("total")));

        orderData.put("today_simple_ride", objectMap.getOrDefault(DataOrderType.simpleCall.getCode(), 0));
        orderData.put("today_phone_ride", objectMap.getOrDefault(DataOrderType.phoneCall.getCode(), 0));
        orderData.put("today", dashboardOrderMinuteMapper.selectObjs(queryWrapper).get(0));
        orderData.put("yesterday", dashboardOrderMinuteMapper.selectObjs(queryWrapperYesterday).get(0));
        orderData.put("lastWeek", dashboardOrderMinuteMapper.selectObjs(queryWrapperLastWeek).get(0));

        // 翻倍率
        Double ride = filterHandler.getFakeMultiple().getRide();
        if (Objects.nonNull(ride)) {
            orderData.forEach((k, v) -> orderData.put(k, (int) (Integer.parseInt(v.toString()) * ride)));
        }

        return orderData;
    }


    /**
     * 获取订单数据
     */
    private Map<String, Object> getRideData(FilterHandler filterHandler, DateTimeHandler time) {
        Map<String, Object> orderData = new HashMap<>();

        QueryWrapper<DashboardOrderMinute> queryWrapper = new QueryWrapper<>();
        QueryWrapper<DashboardOrderMinute> todayQuery = new QueryWrapper<>();
        todayQuery.in("type", DataOrderType.simpleCall, DataOrderType.phoneCall)
                .in("is_imitate", filterHandler.getIsImitates())
                .between("stats_date", time.getTodayBeginning(), time.getToday())
                .select("type, IFNULL(SUM(num), 0) as total")
                .groupBy("type");

        queryWrapper.in("type", DataOrderType.pickOnline, DataOrderType.pickScan, DataOrderType.simpleCall, DataOrderType.phoneCall);
        queryWrapper.in("is_imitate", filterHandler.getIsImitates());
        queryWrapper.select("IFNULL(SUM(num), 0) as total");
        switch (filterHandler.getFilterType()) {
            case canton:
                queryWrapper.in("canton_id", filterHandler.getCantonIds());
                todayQuery.in("canton_id", filterHandler.getCantonIds());
                break;
            case company:
                queryWrapper.in("company_id", filterHandler.getCompanyIds());
                todayQuery.in("company_id", filterHandler.getCompanyIds());
        }
        QueryWrapper<DashboardOrderMinute> queryWrapperYesterday = queryWrapper.clone(), queryWrapperLastWeek = queryWrapper.clone();

        queryWrapper.between("stats_date", time.getTodayBeginning(), time.getToday());
        queryWrapperYesterday.between("stats_date", time.getYesterdayBeginning(), time.getYesterdaySameTime());
        queryWrapperLastWeek.ge("stats_date", time.getLastWeekBeginning()).le("stats_date", time.getLastWeekSameTime());

        // 今日订单
        List<Map<String, Object>> mapList = dashboardOrderMinuteMapper.selectMaps(todayQuery);
        Map<Object, Object> objectMap = mapList.stream().collect(Collectors.toMap(e -> e.get("type"), e -> e.get("total")));

        orderData.put("today_simple_ride", objectMap.getOrDefault(DataOrderType.simpleCall.getCode(), 0));
        orderData.put("today_phone_ride", objectMap.getOrDefault(DataOrderType.phoneCall.getCode(), 0));
        orderData.put("today", dashboardOrderMinuteMapper.selectObjs(queryWrapper).get(0));
        orderData.put("yesterday", dashboardOrderMinuteMapper.selectObjs(queryWrapperYesterday).get(0));
        orderData.put("lastWeek", dashboardOrderMinuteMapper.selectObjs(queryWrapperLastWeek).get(0));

        // 翻倍率
        Double ride = filterHandler.getFakeMultiple().getRide();
        if (Objects.nonNull(ride)) {
            orderData.forEach((k, v) -> orderData.put(k, (int) (Integer.parseInt(v.toString()) * ride)));
        }

        return orderData;
    }

    /**
     * 获取收入数据
     */
    private Map<String, Object> getIncomeData(FilterHandler filterHandler, DateTimeHandler time) {
        Map<String, Object> incomeData = new HashMap<>();

        QueryWrapper<DashboardIncomeMinute> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("is_imitate", filterHandler.getIsImitates());
        queryWrapper.select("IFNULL(SUM(value), 0) as total");
        queryWrapper.eq("through_type", DataIncomeThroughType.all);
        switch (filterHandler.getFilterType()) {
            case canton:
                queryWrapper.in("canton_id", filterHandler.getCantonIds());
                break;
            case company:
                queryWrapper.in("company_id", filterHandler.getCompanyIds());
        }

        QueryWrapper<DashboardIncomeMinute> queryWrapperYesterday = queryWrapper.clone(), queryWrapperLastWeek = queryWrapper.clone();

        queryWrapper.between("stats_date", time.getTodayBeginning(), time.getToday());
        incomeData.put("today", dashboardIncomeMinuteMapper.selectObjs(queryWrapper).get(0));

        queryWrapperYesterday.between("stats_date", time.getYesterdayBeginning(), time.getYesterdaySameTime());
        incomeData.put("yesterday", dashboardIncomeMinuteMapper.selectObjs(queryWrapperYesterday).get(0));

        queryWrapperLastWeek.ge("stats_date", time.getLastWeekBeginning()).le("stats_date", time.getLastWeekSameTime());
        incomeData.put("lastWeek", dashboardIncomeMinuteMapper.selectObjs(queryWrapperLastWeek).get(0));

        // 翻倍率
        Double ride = filterHandler.getFakeMultiple().getRide();
        if (Objects.nonNull(ride)) {
            incomeData.forEach((k, v) -> incomeData.put(k, Double.parseDouble(v.toString()) * ride));
        }

        return incomeData;
    }

    private Map<String, Object> getOpenIncomeData(FilterHandler filterHandler, DateTimeHandler time) {
        Map<String, Object> incomeData = new HashMap<>();

        QueryWrapper<DashboardIncomeMinute> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("is_imitate", filterHandler.getIsImitates());
        queryWrapper.select("IFNULL(SUM(value), 0) as total");
        queryWrapper.eq("through_type", DataIncomeThroughType.all);
        switch (filterHandler.getFilterType()) {
            case canton:
                queryWrapper.in("canton_id", filterHandler.getCantonIds());
                break;
            case company:
                queryWrapper.in("company_id", filterHandler.getCompanyIds());
        }

        QueryWrapper<DashboardIncomeMinute> queryWrapperYesterday = queryWrapper.clone(), queryWrapperLastWeek = queryWrapper.clone();

        queryWrapper.between("stats_date", time.getTodayBeginning(), time.getToday());
        incomeData.put("today", dashboardIncomeMinuteMapper.selectObjs(queryWrapper).get(0));

        queryWrapperYesterday.between("stats_date", time.getYesterdayBeginning(), time.getYesterdayEnd());
        incomeData.put("yesterday", dashboardIncomeMinuteMapper.selectObjs(queryWrapperYesterday).get(0));

        queryWrapperLastWeek.ge("stats_date", time.getLastWeekBeginning()).le("stats_date", time.getLastWeekSameTime());
        incomeData.put("lastWeek", dashboardIncomeMinuteMapper.selectObjs(queryWrapperLastWeek).get(0));

        // 翻倍率
        Double ride = filterHandler.getFakeMultiple().getRide();
        if (Objects.nonNull(ride)) {
            incomeData.forEach((k, v) -> incomeData.put(k, Double.parseDouble(v.toString()) * ride));
        }

        return incomeData;
    }
}
